package xyz.robinbingo.pfboot.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import xyz.robinbingo.pfboot.entity.User;
import xyz.robinbingo.pfboot.repository.UserRepository;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * CustomUserDetailsServiceImpl
 *
 * @author Robin
 * @date 2018/8/1 14:40
 **/
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        Collection<SimpleGrantedAuthority> collection = user.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toSet());
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), collection);
    }
}